/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var deptId = 0;

function viewWorder() {
    var data = getSelectedTr();
    location.href = '/pages/workshop/view_produce_order.php?id=' + data[0] + '&sort=' + data[1] + '&time=' + data[6];
}

$(function() {
    deptId = inputVal('#deptid');

    $('.percentCap').each(function() {
        var n = parseInt($(this).html());
        if (n < 60) {
            $(this).css('color', '#222');
        } else {
            $(this).css('color', '#44b549');
        }
    });

    $('#pdcode1').on('change', function() {
        $("#gmod").find("option[value='" + $(this).find('option:selected').attr('data-productid') + "']")[0].selected = true;
    });

    $('#pdcode2').on('change', function() {
        $("#pmod").find("option[value='" + $(this).find('option:selected').attr('data-productid') + "']")[0].selected = true;
    });

//    // 初始化时间序列
//    $('.workline').each(function(i, node) {
//        mTimer.secs[parseInt($(node).attr('data-cid'))] = parseInt($(node).attr('data-wtime'));
//        mTimer.enable[parseInt($(node).attr('data-cid'))] = false;
//    });

    fnFancyBox('.cbtnInp', function() {

    });

});

function viewWorkonload() {
    //如果是流程的第一个车间，则隐藏上一个车间的div
    if ($('#sort-val').val() == 1) {
        $('#last_department_details_div').hide();
    }
}


function AddProYes() {

}

function timerStart(cid, sec, node) {
    $(node).hide();
    $(node).parent().find('.pause').css('display', 'inline-block');
    mTimer.start(cid, sec);
    changeState(cid, '生产中', -1);
}

function timerPause(cid, node) {
    mTimer.pause(cid);
    changeState(cid, '已暂停', mTimer.secs[cid]);
    $(node).hide();
    $(node).parent().find('.start').css('display', 'inline-block');
}

// 倒计时
function mTimer() {

    var self = this;

    this.call = false;

    this.enable = [];

    this.secs = [];

    this.times = [];

    this.interval = false;

    this.start = function(cid, sec) {
        if (!this.times[cid]) {
            var hour = Math.floor(sec / 3600);
            var minute = Math.floor((sec - hour * 3600) / 60);
            var second = sec - hour * 3600 - minute * 60;
            this.times[cid] = [hour, minute, second];
            this.enable[cid] = true;
            this.secs[cid] = sec;
        } else {
            this.enable[cid] = true;
        }
        if (!this.interval) {
            this.interval = window.setInterval(self.process, 1000);
        }
    };

    /**
     * 暂停计时
     * @param {type} cid
     * @returns {undefined}
     */
    this.pause = function(cid) {
        this.enable[cid] = false;
    };

    this.clear = function() {
        this.interval = false;
    };

    this.process = function() {
        // 一秒执行一次
        var push = false;
        var index = 0;
        var id = 0;
        for (id in self.times) {
            if (self.enable[id]) {
                self.secs[id]++;
                self.times[id][2]++;
                for (index in self.times) {
                    if (push) {
                        self.times[id][2 - index]++;
                        push = false;
                        continue;
                    }
                    if (self.times[id][2 - index] === 60) {
                        self.times[id][2 - index] = 0;
                        push = true;
                    }
                }
                push = null;
                index = null;
                if (self.call) {
                    self.call(id, self.times[id], self.secs[id]);
                }
            }
        }
    };
}

//window.mTimer = new mTimer();
//
//mTimer.call = function(cid, time) {
//    if (typeof time === 'object') {
//        $('#wtime-' + cid).html(time.join(' : '));
//    }
//};

/**
 * 改变工作状态
 * @param {type} cid
 * @param {type} status
 * @param {type} secs
 * @returns {undefined}
 */
function changeState(cid, status, secs) {
    secs = secs || -1;
    $.post('/pages/handler/order_department.php', {
        taskstate: status,
        statement: 'state_update',
        cid: cid,
        worktime: secs
    }
    , function(r) {
        if (parseInt(r) < 1) {
            parent.Alert('操作失败');
        }
    });
}

var ploading = false;

/**
 * 成品添加函数
 * @returns {undefined}
 */
function product_yes_add() {
    var product_wait = 0;
    if ($('#product_yes').val() === '') {
        var product_yes = parseInt($('#now_product_yes').text());
    } else {
        var product_yes = parseInt($('#product_yes').val()) + parseInt($('#now_product_yes').text());
    }
    if ($('#product_no').val() === '') {
        var product_no = parseInt($('#now_product_no').text());
    } else {
        var product_no = parseInt($('#product_no').val()) + parseInt($('#now_product_no').text());
    }
    var cid = parseInt($('#cid').val());
    // 计算待生产数量
    if ($('#front_product_yes').text() === '') {
        product_wait = parseInt($('#product_order_number').text()) - parseInt(product_yes) - parseInt(product_no);
    } else {
        product_wait = parseInt($('#front_product_yes').text()) - parseInt(product_yes) - parseInt(product_no);
    }

    /**
     * 提交数据
     */
    if (!ploading) {
        ploading = true;
        $.post('/pages/handler/order_department.php', {
            cid: cid,
            product_yes: product_yes,
            product_no: product_no,
            product_wait: product_wait,
            worktime: mTimer.secs[cid],
            statement: 'update',
            sort: $('#sort-val').val()
        }, function(r) {
            ploading = false;
            if (parseInt(r) > 0) {
                var n = $('#workline-' + cid);
                parent.Alert('数据录入成功');
                n.find('.productYes').html(product_yes);
                n.find('.productNo').html(product_no);
                n.find('.productWait').html(product_wait);
                n.find('.percentCap').html(parseInt((product_yes + product_no) / parseInt(n.find('.productSum').html()) * 100) + '%');
                $.fancybox.close();
            } else {
                parent.Alert('数据录入失败', 1);
            }
        });
    }
}

/**
 * 输入限制
 * @param {type} node
 * @param {type} val
 * @param {type} lim
 * @returns {undefined}
 */
function checkLimit(node, val, lim) {
    if (val > lim) {
        $(node).val(lim);
    }
}

function loadGRecord() {
    $('#glist').load('/pages/workshop/recordlist.php?mod=g&dept=' + deptId, function() {
        loadWStatus($('#deptid').val());
        dataTableLis();
    });
}

function loadWStatus(dept) {
    dept = dept || '';
    $('#WStatus').load('/pages/workshop/workshop_status.php?dept=' + dept, function() {
        dataTableLis();
    });
}

function loadPRecord() {
    $('#plist').load('/pages/workshop/recordlist.php?mod=p&dept=' + deptId, function() {
        loadWStatus($('#deptid').val());
        dataTableLis();
    });
}

function delGRecord() {

}

function delPRecord() {

}

/**
 * 提交取料记录
 * @returns {undefined}
 */
function submitGRecord() {

    var number = parseFloat(inputVal('#gnumber'));
    var product_id = inputVal('#gmod');
    var fdept = inputVal('#gdept');

    if (number > 0 && product_id !== '' && fdept !== '') {
        $.post('/pages/handler/department_receive_record.php', {
            from_department_id: fdept,
            department_id: deptId,
            product_id: product_id,
            number: number,
            wnumber: $('#wnumber1').val(),
            statement: 'add',
            order_id: $('#pdcode1').val()
        }, function(r) {
            r = parseInt(r);
            if (r > 0) {
                $('#gnumber').val('');
                loadGRecord();
                parent.Alert('提交成功');
            } else {
                parent.Alert('提交失败', true);
            }
        });
    }
}

/**
 * 提交生产记录
 * @returns {undefined}
 */
function submitPRecord() {

    var number = parseFloat(inputVal('#pnumber'));
    var product_id = inputVal('#pmod');

    if (number > 0 && product_id !== '') {
        $.post('/pages/handler/department_product_record.php', {
            department_id: deptId,
            product_id: product_id,
            number: number,
            wnumber: $('#wnumber2').val(),
            statement: 'add',
            order_id: $('#pdcode2').val()
        }, function(r) {
            r = parseInt(r);
            if (r > 0) {
                $('#pnumber').val('');
                loadPRecord();
                parent.Alert('提交成功');
            } else {
                parent.Alert('提交失败', true);
            }
        });
    }
}

function inputVal(id) {
    return $(id).val() ? $(id).val() : 0;
}

/**
 * 删除记录
 * @param {type} id
 * @param {type} mod
 * @param {type} node
 * @returns {undefined}
 */
function recordDelete(id, mod, node) {
    if (id !== '' && mod !== '' && confirm('你确定要删除这个记录吗?')) {
        var url = mod === 'p' ? '/pages/handler/department_product_record.php' : '/pages/handler/department_receive_record.php';
        $.post(url, {
            statement: 'delete',
            id: id
        }, function(r) {
            r = parseInt(r);
            if (r > 0) {
                parent.Alert('删除成功');
                $(node).parent().parent().remove();
            } else {
                parent.Alert('删除失败');
            }
        });
    }
}